﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TiTi.tea.Comm;
using TiTi.tea.Api.Models;
using System.Web.Http;
using System.Net.Http;
using System.Net;
using System.Text;
using System.Web.Http.Controllers;

namespace TiTi.tea.Api.Attributes
{
    public class MyAuthorizeAttribute:AuthorizeAttribute
    {
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            var authHeader = from t in actionContext.Request.Headers
                             where t.Key == "auth"
                             select t.Value.FirstOrDefault();
            if (authHeader != null)
            {
                string token = authHeader.FirstOrDefault();
                if (!string.IsNullOrEmpty(token))
                {
                    try
                    {
                        var obj = JwtHelper.GetDecodingToken(authHeader.FirstOrDefault());
                        if (obj != null)
                        {
                            if (!actionContext.RequestContext.RouteData.Values.ContainsKey("auth"))
                            {
                                //把数据存在RouteData里进行传递。
                                actionContext.RequestContext.RouteData.Values.Add("auth", obj);
                            }
                            return true;
                        }
                    }
                    catch (Exception ex)
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            return false;
        }

        protected override void HandleUnauthorizedRequest(HttpActionContext filterContext)
        {
            base.HandleUnauthorizedRequest(filterContext);

            var response = filterContext.Response = filterContext.Response ?? new HttpResponseMessage();
            response.StatusCode = HttpStatusCode.Forbidden;
            var content = new Result
            {
                code = -1,
                msg = "服务端拒绝访问：你没有权限，或者掉线了"
            };
            response.Content = new StringContent(content.ToJsonItem(), Encoding.UTF8, "application/json");
        }
    }
}